﻿using System;
using System.Net;
using System.Web.Security;
using System.Globalization;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using MvcShop.Models.Repositories;
using System.Web;

namespace MvcShop.Models.Services
{
    #region Services
    // The FormsAuthentication type is sealed and contains static members, so it is difficult to
    // unit test code that calls its members. The interface and helper class below demonstrate
    // how to create an abstract wrapper around such a type in order to make the AccountController
    // code unit testable.

    public interface IMembershipService
    {
        int MinPasswordLength { get; }

        bool ValidateUser(string userName, string password, out int userId);
        bool ValidateRole(int userId,out Role role);
        MembershipCreateStatus CreateUser(RegisterModel register);
        bool ChangePassword(string userName, string oldPassword, string newPassword);
    }

    public class AccountMembershipService : IMembershipService
    {
        private readonly UsersService _provider;
        private readonly UserRepository _userRep;
        private FormsAuthenticationService _formsAS;

        #region ==== Constructors ====
        public AccountMembershipService()
            : this(null,null,null)
        {
        }

        public AccountMembershipService(UsersService provider, UserRepository userRep,FormsAuthenticationService formsAS)
        {
            _provider = provider ?? new UsersService();
            _userRep = userRep ?? new UserRepository();
            _formsAS = formsAS ?? new FormsAuthenticationService();
        }
        #endregion

        #region ==== Property ====
        public int MinPasswordLength
        {
            get
            {
                return _provider.MinRequiredPasswordLength;
            }
        }
        #endregion

        #region ==== IMembershipService ====
        public bool ValidateUser(string userName, string password, out int userId)
        {
            ValidationUtil.ValidateRequiredStringValue(userName, "userName");
            ValidationUtil.ValidateRequiredStringValue(password, "password");

            return _provider.ValidateUser(userName, _formsAS.HashPasswordForStoringInConfigFile(password), out userId);
        }

        public bool ValidateRole(int userId, out Role role)
        {
            return _provider.ValidateRole(userId, out role);
        }

        public MembershipCreateStatus CreateUser(RegisterModel register)
        {
            ValidationUtil.ValidateRequiredStringValue(register.UserName, "userName");
            ValidationUtil.ValidateRequiredStringValue(register.Password, "password");
            ValidationUtil.ValidateRequiredStringValue(register.Email, "email");

            MembershipCreateStatus mc = MembershipCreateStatus.Success; 
            if(_userRep.FindUserByName(register.UserName))
            {
                mc = MembershipCreateStatus.DuplicateUserName;
            }
            if(_userRep.FindUserByEmail(register.Email))
            {
                mc = MembershipCreateStatus.DuplicateEmail;
            }
            if (mc == MembershipCreateStatus.Success)
            {
                try
                {
                    var user = new User();
                    user.UserName = register.UserName;
                    user.Password = _formsAS.HashPasswordForStoringInConfigFile(register.Password);
                    user.Email = register.Email;
                    user.LastLoginIP = CustomerIP.GetIP();
                    user.LastLoginTime = DateTime.Now;
                    user.LastLogoutTime = DateTime.Now.AddMinutes(30);
                    user.LoginTimes = 1;

                    this._userRep.Add(user);
                    this._userRep.SaveChanges();
                }catch(Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
             return mc;
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            ValidationUtil.ValidateRequiredStringValue(userName, "userName");
            ValidationUtil.ValidateRequiredStringValue(oldPassword, "oldPassword");
            ValidationUtil.ValidateRequiredStringValue(newPassword, "newPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            try
            {
                return _provider.ChangePassword(userName, _formsAS.HashPasswordForStoringInConfigFile(oldPassword), _formsAS.HashPasswordForStoringInConfigFile(newPassword));
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }
        #endregion
    }

    public interface IFormsAuthenticationService
    {
        void SignIn(string userName, bool createPersistentCookie);
        void SignOut();
        string HashPasswordForStoringInConfigFile(string password);
    }

    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            ValidationUtil.ValidateRequiredStringValue(userName, "userName");

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        public string HashPasswordForStoringInConfigFile(string password)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");//SHA1/MD5
        }
    }

    internal static class ValidationUtil
    {
        private const string _stringRequiredErrorMessage = "值不能为空。";

        public static void ValidateRequiredStringValue(string value, string parameterName)
        {
            if (String.IsNullOrEmpty(value))
            {
                throw new ArgumentException(_stringRequiredErrorMessage, parameterName);
            }
        }
    }
    #endregion


    #region ==== Validation ====
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class PropertiesMustMatchAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' 和 '{1}' 不匹配。";

        public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
            : base(_defaultErrorMessage)
        {
            OriginalProperty = originalProperty;
            ConfirmProperty = confirmProperty;
        }

        public string ConfirmProperty
        {
            get;
            private set;
        }

        public string OriginalProperty
        {
            get;
            private set;
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                OriginalProperty, ConfirmProperty);
        }

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
            object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
            return Object.Equals(originalValue, confirmValue);
        }
    }

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class ValidatePasswordLengthAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' 必须至少 {1} 个字符。";

        private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;

        public ValidatePasswordLengthAttribute()
            : base(_defaultErrorMessage)
        {
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                name, _minCharacters);
        }

        public override bool IsValid(object value)
        {
            string valueAsString = value as string;
            if (String.IsNullOrEmpty(valueAsString))
            {
                return true;
            }

            return (valueAsString.Length >= _minCharacters);
        }
    }
    #endregion

    #region ==== CustomerIP ====
    public static class CustomerIP
    {
        /// <summary>
        /// 获取当前请求的IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            //获取IP地址
            HttpRequest request = HttpContext.Current.Request;
            string ipAddress = string.Empty;
            if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null || request.ServerVariables["HTTP_X_FORWARDED_FOR"] == "")
            {
                ipAddress = request.ServerVariables["REMOTE_ADDR"];
            }
            else if (request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",") >= 0)
            {
                int index = request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",");
                ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(0, index - 1);
            }
            else if (request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";") >= 0)
            {
                int index = request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";");
                ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(0, index - 1);
            }
            else
            {
                ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }
            if (ipAddress == "127.0.0.1")
            {
                ipAddress = GetLocalhostIPAddress();
            }
            return ipAddress;
        }
        /// <summary>
        /// 获取本机IP
        /// </summary>
        /// <returns></returns>
        private static string GetLocalhostIPAddress()
        {
            string hostName = System.Net.Dns.GetHostName();
            System.Net.IPHostEntry hostInfo = System.Net.Dns.GetHostByName(hostName);
            System.Net.IPAddress[] IpAddr = hostInfo.AddressList;
            string localIP = string.Empty;
            for (int i = 0; i < IpAddr.Length; i++)
            {
                localIP += IpAddr[i].ToString();
            }
            return localIP;
        } 
    }
    #endregion
}
